
// get parameters from request body|query|params
// if the parameter in request can not be found , it will return undefined
const getParam = (req, list) => {
  if (!isArray(list)) {
    console.error('>> error: list should be an array!')
    return null
  }
  let result = {}
  list.map(value => {
    result[value] = req.body[value] === undefined
      ? (req.query[value] === undefined
        ? (req.params[value] === undefined
          ? undefined
          : req.params[value])
        : req.query[value])
      : req.body[value]
  })
  return result
}

// get host address from request headers
const getIP = (req) => {
  return req.headers.origin || req.headers.referer || req.headers.host
}

// check if token is passed 
// use : if (isNoToken(req, res)) return
const noTokenResponse = {code: -2, message: 'user is not login, please login first.', uri: '/login'}
const isNoToken = (req, res) => {
  const { token } = getParam(req, ['token'])
  if (!token) {
    res.json(noTokenResponse)
    return 1
  }
  return 0
}

// check the obj is an array or not
const isArray = (obj) => Object.prototype.toString.call(obj) === '[object Array]'

const isInArray = (arr, field, value) => {
  let flag = false
  arr.map(item => {
    if (item[field] === value) {
      flag = true
    }
  })
  return flag
}

module.exports = {
  getParam,
  getIP,
  isNoToken,
  isInArray
}
